package com.paul.sys.tools;

import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamReader;
import java.io.BufferedOutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

public class LocationOper {

	private static final String URL_STR = "http://search1.mapabc.com/sisserver";
	private static final String DISTANCE_PARAM="config=R&enc=gbk&resType=xml&routeType=0&x1=%f&x2=%f&y1=%f&y2=%f&a_k=8ba7c38d14da8249f144e8505c49278c2476d8f994db5243eb32207e56ac9d44cb5faf15e2e2a132";
	private static final String DISTANCE_PARAM1="config=R&ver=2.0&enc=gbk&resType=xml&routeType=%d&xs=%s&ys=%s&a_k=8ba7c38d14da8249f144e8505c49278c2476d8f994db5243eb32207e56ac9d44cb5faf15e2e2a132";

	public static String[] distance(double x1, double y1, double x2, double y2,int routeType) throws Exception {
		HttpURLConnection httpConnection=null;
		OutputStreamWriter osw = null;
		String[] result=new String[2];
		
		try {
			URL url = new URL(URL_STR);
			httpConnection = (HttpURLConnection) url.openConnection();
			httpConnection.setConnectTimeout(1000 * 10);
			httpConnection.setRequestProperty("Connection","Keep-Alive"); 
			httpConnection.setRequestMethod("POST");
			httpConnection.setDoInput(true);
			httpConnection.setDoOutput(true);
			httpConnection.setAllowUserInteraction(true);
			httpConnection.connect();	
			
			String param=String.format(DISTANCE_PARAM1,routeType, x1+","+x2,y1+","+y2);
			osw = new OutputStreamWriter(new BufferedOutputStream(
					httpConnection.getOutputStream()));
			osw.write(param);
			osw.flush();
			// 读取结果
			
			XMLInputFactory factory = XMLInputFactory.newInstance();
			XMLStreamReader r = factory.createXMLStreamReader(httpConnection.getInputStream());
			int distance=0;
			try{
				int event=r.getEventType();
				while(true){
					switch(event){
					case  XMLStreamConstants.START_ELEMENT:						
						String name=r.getName().toString();
						if(name.equals("roadLength")){
							distance+=Integer.parseInt(r.getElementText());
						}else if(name.equals("coors")){
							result[1]=r.getElementText();
						}
					
					}
					if (!r.hasNext())
						 break;
					event = r.next();
				}
				result[0]=String.valueOf(distance);
			} finally{
				r.close();
			}

		} finally {
			try {
				osw.close();
			} catch (Exception e2) {
			}			
			try {
				httpConnection.disconnect();
			} catch (Exception e2) {
			}
		}
		return result;
	}

}
